<script>
import {dictionaryRequest, uploadFile} from "../../../util/js/globalRequestJs";
import {checkFileSize, formatDate} from "../../../util/js/utils";
import {addNotice} from "./insertNoticeJs";

export default {
  name: "InsertNotice",
  data() {
    return {
      noticeTitle: '',
      noticeContext: '',
      fileList: [],
      types: [],
      type: '',
      deadline: '',
      priority: ''
    }
  },
  mounted() {
    dictionaryRequest('notice', 'type').then(res => {
      this.types = res.data;
    }).catch(error => {
      this.$router.push('/framework/error')
      console.log(error);
    })
  },
  methods: {
    handleFileChange(event) {
      // 从事件中获取选择的文件
      const file = event.target.files[0];
      var name = file.name;

      if (!checkFileSize(file)) {
        this.$message.error('File size should be less than 1M, please upload again!');
        return;
      }

      let formData = new FormData();
      formData.append('file', file);
      // 发送请求到后端进行处理
      uploadFile(formData).then(res => {
        if (res.code === '200') {
          this.fileList.push({
            name: name,
            url: res.data
          });
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(err => {
        this.$router.push('/framework/error')
        console.log('系统出错了', err);
      })
    },
    // 触发上传
    uploadFile() {
      // 触发隐藏的文件选择器点击事件
      this.$refs.fileInput.click();
    },
    // 移除上传的文件
    removeFile(index) {
      this.fileList.splice(index, 1);
    },
    // 新增公告
    submitNotice() {
      if (this.noticeTitle === '') {
        this.$message.warning("请填写标题！")
        return false;
      }
      if (this.type === '') {
        this.$message.warning("请选择公告类型！")
        return false;
      }
      if (this.deadline === '') {
        this.$message.warning("请选择过期时间！")
        return false;
      }
      if (this.priority === '') {
        this.$message.warning("请选择优先级！")
        return false;
      }
      if (this.noticeContext === '') {
        this.$message.warning("请填写公告内容！")
        return false;
      }
      const noticeData = {
        "title": this.noticeTitle,
        "context": this.noticeContext,
        "annex": JSON.stringify(this.fileList.map(item => ({ name: item.name, url: item.url }))),
        "type": this.type,
        "deadline": this.deadline,
        "priority": this.priority
      }
      addNotice(noticeData).then(res => {
        if (res.code === '200') {
          this.$message.success("添加成功！")
          // 清空页面内容
          this.noticeTitle = '';
          this.noticeContext = '';
          this.fileList = [];
          this.type = '';
          this.deadline = '';
          this.priority = '';
        } else {
          this.$message.error("添加失败：" + res.msg);
        }
      }).catch(err => {
        this.$router.push('/framework/error')
        console.log(err);
      })
    }
  }
}
</script>

<template>
  <div id="in-main-container" class="in-main-container">
    <div style="font-size: 20px;font-family: 正楷;text-align: center;margin-bottom: 20px;">
      新增公告
    </div>
    <div id="in-title-container" class="in-span-container">
      <span>标题：</span>
      <el-input
        placeholder="请输入内容"
        v-model="noticeTitle"
        size="small"
        clearable>
      </el-input>
    </div>
    <div id="in-attr-container">
      <div style="display: flex;" class="in-span-container">
        <span style="width: 89px;">公告类型：</span>
        <el-select v-model="type" style="width: 200px"
                   slot="prepend" placeholder="请选择公告类型" size="small">
          <el-option
            v-for="option in types"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          ></el-option>
        </el-select>
      </div>
      <div style="display: flex;" class="in-span-container">
        <span style="width: 89px;">过期时间：</span>
        <el-date-picker
          style="width: 200px; height: 32px;"
          v-model="deadline"
          type="datetime"
          size="small"
          placeholder="选择过期时间">
        </el-date-picker>
      </div>
      <div style="display: flex;" class="in-span-container">
        <span style="width: 89px;">优先级：</span>
        <el-select v-model="priority" style="width: 200px"
                   slot="prepend" placeholder="优先级" size="small">
          <el-option label="一级" value="1"></el-option>
          <el-option label="二级" value="2"></el-option>
          <el-option label="三级" value="3"></el-option>
          <el-option label="四级" value="4"></el-option>
          <el-option label="五级" value="5"></el-option>
          <el-option label="六级" value="6"></el-option>
        </el-select>
        <span style="width: 120px;font-size: 15px;">（1 --> 6）级</span>
      </div>

    </div>
    <div id="in-context-container" class="in-span-container">
      <span>内容：</span>
      <div style="width: 100%">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="noticeContext"
          :autosize="{ minRows: 8, maxRows: 8}"
          maxlength="200"
          show-word-limit>
        </el-input>
      </div>
    </div>
    <div id="in-upload-container" class="in-span-container">
      <span style="width: 89px">附件：</span>
      <div>
        <el-button @click="uploadFile" type="primary" size="small" plain>上传附件</el-button>
        <!-- 隐藏的文件选择器 -->
        <input ref="fileInput" type="file" style="display: none" @change="handleFileChange">
        <div slot="tip" class="el-upload__tip">只能上传doc/docx文件，且不超过1MB</div>
        <span v-for="(file,index) in fileList" :key="index"
              :style="{ fontSize: '12px', border: file.hover ? '1px solid #ccc' : 'none',
               backgroundColor: file.hover ? '#cccccc' : 'transparent' }"
              @mouseover="file.hover = true" @mouseout="file.hover = false">
          <i class="el-icon-tickets"></i>
          {{ file.name }}
          <a @click="removeFile(index)" style="margin-left: 50px;">
            <i class="el-icon-circle-close"></i></a>
          <br/>
        </span>
      </div>
    </div>
    <div id="in-submit-container" class="in-submit-container">
      <el-button type="primary" @click="submitNotice" style="width: 200px" size="small" plain>提交</el-button>
    </div>
  </div>
</template>

<style scoped>
@import "insertNoticeCss.css";
</style>
